package cn.edu.hizee.gps.controller;

import cn.edu.hizee.gps.dao.*;
import cn.edu.hizee.gps.model.ActionNode;
import cn.edu.hizee.gps.model.Admin;
import cn.edu.hizee.gps.model.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("public")
public class PublicController extends BaseController{


    @Autowired
    private PublicRepository publicRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ActionNodeRepository actionNodeRepository;

    @Autowired
    private ContactRepository contactRepository;

    @Autowired
    private SiteRepository siteRepository;

    @Autowired
    private RedisTemplate redisTemplate;
    private String NAME = "Excel导入";

    @RequestMapping("a")
    public String a(HttpServletResponse response){
        List<ActionNode> menuList = actionNodeRepository.findAll();
        return ajaxReturn(response,menuList);
    }


    @RequestMapping("index")
    public String index(Model model,HttpServletResponse response){
        List<ActionNode> menuList = actionNodeRepository.findAll();
        model.addAttribute("MenuList", menuList);

        List<User> list = userRepository.findAll();
        model.addAttribute("userList",list);

        List<Map> dangerPeople = siteRepository.findAllDangerPeople();
        model.addAttribute("dangerList",dangerPeople);

        model.addAttribute("fregUrl","user_list");
        return "public/index";
    }

    @RequestMapping(value = "login")
    public String login(Admin user, HttpServletRequest request, HttpServletResponse response){
        Admin entity = publicRepository.findByUsernameAndPassword(user.getUsername(), DigestUtils.md5Hex(user.getPassword()));
        if(entity != null) {
            request.getSession().setAttribute("Admin", entity);
            return ajaxReturn(response, 1, "登录成功", null);
        } else {
            return ajaxReturn(response, 0, "账号或密码错误", null);
        }
    }

    @PostMapping("cancel")
    public String cancel(String userId, String type,HttpServletResponse response){
        System.out.println(userId + " " + type);
        if(type.equals("3")){
            siteRepository.deleteByUserId(Integer.valueOf(userId));
        }else {
            redisTemplate.opsForValue().set(userId + "type" + type, null);
        }
        return ajaxReturn(response, (HashMap<String, Object>) null);
    }
}
